<template>
  <Dialog
    :visible="visible"
    :title="isEdit ? '修改角色' : '新增角色'"
    width="500px"
    footer-type="custom"
    @update:visible="handleUpdateVisible"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
      label-position="left"
    >
      <el-form-item label="角色名" prop="roleName">
        <el-input
          v-model="formData.roleName"
          placeholder="请输入角色名"
          maxlength="16"
          show-word-limit
          clearable
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ isEdit ? '修改' : '新增' }}
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick, computed } from 'vue'
import { type FormInstance, type FormRules } from 'element-plus'
import { api } from '@/api'
import { success, error } from '@/utils/toast'
import Dialog from '@/components/BaseDialog.vue'

// Props
interface Props {
  modelValue: boolean
  roleData?: any
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  roleData: () => null
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  roleName: ''
})

// 表单验证规则
const rules: FormRules = {
  roleName: [
    { required: true, message: '请输入角色名', trigger: 'blur' },
    { min: 1, max: 16, message: '角色名长度在 1 到 16 个字符', trigger: 'blur' }
  ]
}


// 计算属性
const isEdit = computed(() => {
  return !!(props.roleData && props.roleData.roleId)
})

// 监听器
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val
    if (val) {
      initFormData()
    }
  }
)

watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 初始化表单数据
const initFormData = () => {
  if (props.roleData) {
    formData.roleName = props.roleData.roleName || ''
  } else {
    formData.roleName = ''
  }
  
  // 清除验证状态
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    if (isEdit.value) {
      // 修改角色 - 只传入角色名
      await api.role.updateRole(props.roleData.roleId, formData.roleName)
      success('修改成功')
    } else {
      // 新增角色 - 只传入角色名
      await api.role.createRole(formData.roleName)
      success('新增成功')
    }
    
    emit('success')
    handleClose()
  }  finally {
    loading.value = false
  }
}

// 处理 BaseDialog 的 visible 更新
const handleUpdateVisible = (value: boolean) => {
  visible.value = value
  emit('update:modelValue', value)
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  formRef.value?.resetFields()
}

// 暴露方法
defineExpose({
  open: () => {
    visible.value = true
    // 注意：这里不能直接修改 props，需要通过父组件传递
  },
  close: handleClose
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}
</style>
